/*
 * Copyright (C) 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.codemirror2_gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;

/**
 * Describes a CodeMirror text change.
 * 
 * @author Bobby Soares
 */
public class TextChange extends JavaScriptObject {

  protected TextChange() { }
  
  /**
   * Retrieves the start position of the replaced text.
   * 
   * @return the start position of the replaced text 
   */
  public final native Cursor getFrom() /*-{
    return this.from;
  }-*/;
  
  /**
   * Retrieves the end position of the replaced text.
   * 
   * @return the end position of the replaced text 
   */
  public final native Cursor getTo() /*-{
    return this.to;
  }-*/;
  
  /**
   * Retrieves the text lines that replace the deleted text.
   * 
   * @return a string array containing the replacement lines
   */
  public final String[] getText() {
    return toArray(getTextNative());
  }
  
  /**
   * Retrieves the replacement lines as a native JavaScript string array.
   * 
   * @return the native replacement lines
   */
  private final native JsArrayString getTextNative() /*-{
    return this.text;
  }-*/;
  
  /**
   * Converts a native JavaScript string array object to a string array.
   * 
   * @param values the array to convert
   * @return the corresponding string array
   */
  private static String[] toArray(JsArrayString values) {
    if (GWT.isScript()) {
      return reinterpretCast(values);
    } else {
      int length = values.length();
      String[] ret = new String[length];
      for (int i = 0, l = length; i < l; i++) {
        ret[i] = values.get(i);
      }
      return ret;
    }
  }
  
  /**
   * Reinterprets a native JavaScript string array object as a string array.
   * Note: this cast is safe outside of hosted mode.
   * 
   * @param value the native array object to reinterpret
   * @return the value as a string array
   */
  private static native String[] reinterpretCast(JsArrayString value) /*-{
    return value;
  }-*/;
}

